/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.webbapps.cormac_susilo.core;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;


/**
 * Implements Methods specific to the User-part of the model / database
 * @author simon, tor
 */
public final class UserRegistry extends AbstractDAO<User, Long> {

    private UserRegistry(String puName){
        super(User.class, puName);
    }
    
    /**
     * Factory method
     * @param puName
     * @return 
     */
    public static UserRegistry newInstance(String puName) {
        return new UserRegistry(puName);
    }
    
    /**
     * Find a single user with this username
     * @param user_name the name to look for
     * @return the User object if it is found, otherwise null
     */
    public User findByName(String user_name) {
        EntityManager em = super.getEM();

        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<User> cq = cb.createQuery(User.class);
        Root<User> user = cq.from(User.class);

        cq.where(cb.equal(user.get(User_.name), user_name));

        User result = null;
        try {
            result = em.createQuery(cq).getSingleResult();
        } catch (NoResultException e) {
            //this is fine, we will return null
        }
        em.close();

        return result;
    }
}
